package com.zcah.config;


import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;


@Configuration

public class ElasticsearchConfig {

    Logger logger = LoggerFactory.getLogger(ElasticsearchConfig.class);
    private String esHost = "192.168.188.191:9300,192.168.188.192:9300,192.168.188.221:9300";
    private String esClusterName = "es-cluster";

    @Bean
    public Client client() throws Exception {

        Settings settings = Settings.builder().put("cluster.name", esClusterName)
                .put("client.transport.sniff", true) // 探测集群中机器状态
                .put("discovery.zen.ping_timeout", "5s").build();
        PreBuiltTransportClient client = new PreBuiltTransportClient(settings);
        String[] hosts = esHost.split(",");
        try {
            for (String host : hosts) {
                String[] address = host.split(":");
                client.addTransportAddress(
                        new InetSocketTransportAddress(InetAddress.getByName(address[0]), Integer.parseInt(address[1])));
                logger.info("create client");
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return client;
    }
}